package com.tuju.jetpackfirstdemo.ui.mpchart;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.google.gson.Gson;
import com.tuju.jetpackfirstdemo.R;
import com.tuju.jetpackfirstdemo.utils.KLineHelper;
import com.tuju.jetpackfirstdemo.utils.TextResourceReader;

import java.util.ArrayList;
import java.util.List;

public class MPAndroidChartActivity extends AppCompatActivity {

    private LineChart chart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mpandroid_chart);
        initView();
        initData();
    }

    private void initView() {
        chart = findViewById(R.id.k_view);

        // apply styling
        // chart.setValueTypeface(mTf);
        chart.getDescription().setEnabled(false);
        chart.setDrawGridBackground(false);
//        chart.setScaleEnabled(false);

        //定义X轴
        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(true);
        xAxis.setLabelRotationAngle(60);
        KLineHelper.MyXFormattrt formatter = new KLineHelper.MyXFormattrt();
        xAxis.setValueFormatter(formatter);

        //定义Y轴
        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setLabelCount(5, false);
        leftAxis.setDrawGridLines(false);//画点的辅助线
        leftAxis.setDrawAxisLine(true);
        KLineHelper.MyYFormattrt formattrtY = new KLineHelper.MyYFormattrt();
        leftAxis.setValueFormatter(formattrtY);

        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setDrawAxisLine(false);
        rightAxis.setDrawLabels(false);//不画右侧Y轴

        //markView弹窗
        KLineHelper.MyMarkerView mv = new KLineHelper.MyMarkerView(this, R.layout.view_markview);
        mv.setChartView(chart);
        chart.setMarker(mv);
        chart.animateXY(500, 500);
        chart.setOnChartGestureListener(new KLineHelper.CoupleChartGestureListener() {
            @Override
            public void onChartDoubleTapped(MotionEvent me) {
                doubleTapped();
            }
        });//设置手势联动监听
    }

    private void doubleTapped() {
        if (isPort()) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    /**
     * 当前是否是竖屏
     */
    public boolean isPort() {
        return getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    @Override
    public void onBackPressed() {
        if (isPort()) {
            super.onBackPressed();
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    private void initData() {
        String result = TextResourceReader.readTextFileFromAssets(this, "kline2.json");
        KLineBean beanResult = new Gson().fromJson(result, KLineBean.class);
        List<List<KLineBean.PointBean>> lines = new ArrayList<>();
        List<String> products = new ArrayList<>();
        for (int i = 0; i < beanResult.getMessage().getProducts().size(); i++) {
            lines.add(beanResult.getMessage().getProducts().get(i).getData());
            products.add(beanResult.getMessage().getProducts().get(i).getProductName());
        }
        resetDrawLine(beanResult.getMessage().getY(), beanResult.getMessage().getX(), lines, products);
    }


    //绘制折线
    public void resetDrawLine(List<Float> yDatas, List<String> xTime, List<List<KLineBean.PointBean>> dataValue, List<String> productName) {
        List<Float> yMinMax = KLineHelper.getMaxMinY(yDatas, null);
        float minValueY = yMinMax.get(0);
        float maxValueY = yMinMax.get(1);

        List<Long> xMinMax = KLineHelper.getMaxMinX(xTime, null);
        long minValueX = xMinMax.get(0);
        long maxValueX = xMinMax.get(1);

        //定义X轴
        XAxis xAxis = chart.getXAxis();
        xAxis.resetAxisMaximum();
        xAxis.resetAxisMinimum();
        xAxis.setLabelCount(xTime.size(), true);
        xAxis.setAxisMinimum(minValueX);
        xAxis.setAxisMaximum(maxValueX);

        //定义Y轴
        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.resetAxisMaximum();
        leftAxis.resetAxisMinimum();
        leftAxis.setLabelCount(yDatas == null ? 10 : yDatas.size(), false);
        leftAxis.setAxisMaximum(maxValueY);
        leftAxis.setAxisMinimum(minValueY);

        ArrayList<ILineDataSet> sets = new ArrayList<>();
        for (int i = 0; i < dataValue.size(); i++) {
            List<KLineBean.PointBean> pointDataList = dataValue.get(i);
            List<Entry> values1 = new ArrayList<>();
            for (int j = 0; j < pointDataList.size(); j++) {
                values1.add(new Entry(KLineHelper.dateToStamp(pointDataList.get(j).getX()), pointDataList.get(j).getY()));
            }
            String deviceName = "设备" + i;
            if (!productName.isEmpty() && i < productName.size()) {
                deviceName = productName.get(i);
            }

            LineDataSet d1 = new LineDataSet(values1, deviceName);
            d1.setLineWidth(2.5f);
            d1.setCircleRadius(4.5f);
            int color = KLineHelper.randomColor();
            d1.setColor(color);
            d1.setHighLightColor(color);//点击后交叉线颜色
            d1.setDrawValues(true);
            d1.setDrawCircles(false);//是否画出点所在的圆
            d1.setMode(LineDataSet.Mode.CUBIC_BEZIER);//圆滑贝塞尔曲线

            sets.add(d1);
        }
        chart.setData(new LineData(sets));
        chart.notifyDataSetChanged();
        chart.invalidate();
    }

    public void kLine2(View view) {
        Intent intent = new Intent(this, LineChartActivity.class);
        startActivity(intent);
    }

}
